package redis

import (
	"fmt"

	"github.com/go-redis/redis"
	"github.com/spf13/viper"
)

var rdb *redis.Client

type redisStruct struct {
	Addr     string `mapsturcture:"addr"`
	Port     string `mapsturcture:"port"`
	Password string `mapsturcture:"password"`
	Db       int    `mapsturcture:"db"`
	PoolSize int    `mapsturcture:"pool_size"`
}

var redisConfig = new(redisStruct)

func Init() (err error) {
	sub := viper.Sub("redis")
	_ = sub.Unmarshal(redisConfig)
	str := fmt.Sprintf("%s:%s", redisConfig.Addr, redisConfig.Port)
	rdb = redis.NewClient(&redis.Options{
		Addr:     str,
		Password: redisConfig.Password,
		DB:       redisConfig.Db,
		PoolSize: redisConfig.PoolSize,
	})
	_, err = rdb.Ping().Result()
	if err != nil {
		return err
	}
	return nil
}

func Close() {
	_ = rdb.Close()
}
